package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.exception.NoStockeException;
import com.atguigu.gulimall.ware.feign.OrderFeignServcice;
import com.atguigu.gulimall.ware.feign.ProductFeign;
import com.atguigu.common.to.HasStockTo;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private WareSkuDao wareSkuDao;
    @Resource
    private ProductFeign productFeign;
    @Resource
    WareOrderTaskService wareOrderTaskService;
    @Resource
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    OrderFeignServcice orderFeignServcice;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        String wareId = (String) params.get("wareId");
        wrapper.eq(StringUtils.isNotBlank(wareId), WareSkuEntity::getWareId, wareId);
        String skuId = (String) params.get("skuId");
        wrapper.eq(StringUtils.isNotBlank(skuId), WareSkuEntity::getSkuId, skuId);
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(List<PurchaseDetailEntity> entities) {
        for (PurchaseDetailEntity entity : entities) {
            List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new LambdaQueryWrapper<WareSkuEntity>().eq(WareSkuEntity::getSkuId, entity.getSkuId()).eq(WareSkuEntity::getWareId, entity.getWareId()));
            if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
                WareSkuEntity wareSkuEntity = new WareSkuEntity();
                wareSkuEntity.setSkuId(entity.getSkuId());
                wareSkuEntity.setStock(entity.getSkuNum());
                wareSkuEntity.setWareId(entity.getWareId());
                wareSkuEntity.setStockLocked(0);
                try {
                    R info = productFeign.info(entity.getSkuId());
                    if (info.getCode() == 0) {
                        Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                        wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                    }
                } catch (Exception e) {

                }
                this.baseMapper.insert(wareSkuEntity);
                //insert
            } else {
                //update
                wareSkuDao.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
        }
    }

    @Override
    public List<HasStockTo> getSkuStock(List<Long> skuIds) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        wrapper.in("sku_id", skuIds);
        wrapper.groupBy("sku_id");
        wrapper.select("IFNULL(sum(stock-stock_locked),0) as stock","sku_id");
        List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(wrapper);
        List<HasStockTo> collect = wareSkuEntities.stream().map(item -> {
            HasStockTo vo = new HasStockTo();
            vo.setSkuId(item.getSkuId());
            vo.setHasStock(item.getStock()!=null&&item.getStock()>0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param vo
     * @return
     *
     * 库存解锁的场景
     * 1、下订单成功，订单过期没有支付被系统自动取消、被用户手动取消
     *
     * 2、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     *
     */
    @Transactional(rollbackFor = NoStockeException.class)
    @Override
    public Boolean orderLock(WareSkuLockVo vo) {
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //1、按照下单的收货地址  找到一个就近仓库，锁定库存

        //1.找到每个商品在哪个仓库有库存就从哪个仓库发货
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock hasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            hasStock.setSkuId(skuId);
            hasStock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            hasStock.setWareIds(wareIds);
            return hasStock;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWareHasStock stock : collect) {
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareIds();
            if(wareIds==null||wareIds.size()==0){
                throw new NoStockeException(skuId.toString());
            }
            Boolean lock = false;
            for (Long wareId : wareIds) {
               Long count = wareSkuDao.lockSkuStock(skuId,wareId,stock.getNum());
               if(count==1){
                   //当前仓库锁失败
                   WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,skuId,skuId.toString(),stock.getNum(),taskEntity.getId(),wareId,1);
                   wareOrderTaskDetailService.save(detailEntity);
                   StockLockTo lockTo = new StockLockTo();
                   lockTo.setId(taskEntity.getId());
                   StockDetailTo detailTo = new StockDetailTo();
                   BeanUtils.copyProperties(detailEntity,detailTo);
                   lockTo.setDetail(detailTo);
                   rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockTo);
                   lock=true;
               }
            }
            if(!lock){
                throw new NoStockeException(skuId.toString());
            }
        }
        return true;
    }

    /**
     *  只要解锁库存的信息失败。一定要告诉服务解锁失败  启动手动ack 机制
     * @param to
     * @param message
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleStockLockedRelease(StockLockTo to, Message message,Channel channel) throws IOException {
        System.err.println("收到解锁库存的消息");
        Long id = to.getId();
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if(detailEntity!=null){
            Long taskId = detailEntity.getTaskId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignServcice.getOrderStatus(orderSn);
            if(r.getCode()==0){
                OrderTo data = r.getData("data", new TypeReference<OrderTo>() {
                });
                if(data!=null){
                    // 查到该订单，根据订单状态 判断订单库存是否需要解锁
                    if(data.getStatus()==4){
                        if(detailEntity.getLockStatus()==1){
                            unlockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                        }
                    }
                }else {
                    //查不到该订单 直接解锁
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }
            }else {
                //拒绝消息，放回队列
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    /**
     *     防止订单服务 卡顿，导致订单状态消息一直改不了，库存消息有限到期。
     *     查订单状态 新建状态，什么都不做就走了，导致卡顿的订单，永远不能解锁库存
     */


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) {
        String orderSn = to.getOrderSn();

        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : list) {
            unlockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    void unlockStock(Long skuId, Long wareId, Integer num, Long detailId) {
        wareSkuDao.unlockStock(skuId,wareId,num);

        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(detailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }


    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareIds;
    }


}